package com.landinfo.web.rest;

import com.codahale.metrics.annotation.Timed;
import com.landinfo.domain.DataType;
import com.landinfo.service.DataTypeService;
import com.landinfo.service.dto.DataType2DTO;
import com.landinfo.web.rest.util.HeaderUtil;
import com.landinfo.service.dto.DataTypeDTO;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;

import java.util.List;
import java.util.Optional;

/**
 * REST controller for managing DataType.
 */
@RestController
@RequestMapping("/api")
public class DataTypeResource {

    private final Logger log = LoggerFactory.getLogger(DataTypeResource.class);

    private static final String ENTITY_NAME = "dataType";

    private final DataTypeService dataTypeService;


    public DataTypeResource(DataTypeService dataTypeService) {
        this.dataTypeService = dataTypeService;
    }

    /**
     * POST  /data-types : Create a new dataType.
     *
     * @param dataTypeDTO the dataTypeDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new dataTypeDTO, or with status 400 (Bad Request) if the dataType has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/data-types")
//    @CacheEvict(value = {"DataTypeCache"}, allEntries = true)
    @Timed
    public ResponseEntity<DataTypeDTO> createDataType(@Valid @RequestBody DataTypeDTO dataTypeDTO) throws URISyntaxException {
        log.debug("REST request to save DataType : {}", dataTypeDTO);
//        if (dataTypeDTO.getId() != null) {
//            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new dataType cannot already have an ID")).body(null);
//        }
        DataTypeDTO result = dataTypeService.save(dataTypeDTO);
        return ResponseEntity.created(new URI("/api/data-types/" + result.getId()))
                .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
                .body(result);
    }

    /**
     * PUT  /data-types : Updates an existing dataType.
     *
     * @param dataTypeDTO the dataTypeDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated dataTypeDTO,
     * or with status 400 (Bad Request) if the dataTypeDTO is not valid,
     * or with status 500 (Internal Server Error) if the dataTypeDTO couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/data-types")
//    @CacheEvict(value = {"DataTypeCache"}, allEntries = true)
    @Timed
    public ResponseEntity<DataTypeDTO> updateDataType(@Valid @RequestBody DataTypeDTO dataTypeDTO) throws URISyntaxException {
        log.debug("REST request to update DataType : {}", dataTypeDTO);
        if (dataTypeDTO.getId() == null) {
            return createDataType(dataTypeDTO);
        }
        DataTypeDTO result = dataTypeService.save(dataTypeDTO);
        return ResponseEntity.ok()
                .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, dataTypeDTO.getId().toString()))
                .body(result);
    }

    /**
     * GET  /data-types : get all the dataTypes.
     *
     * @return the ResponseEntity with status 200 (OK) and the list of dataTypes in body
     */
    @GetMapping("/data-types")
//    @Cacheable(value = "DataTypeCache")
    @Timed
    public List<DataTypeDTO> getAllDataTypes() {
        log.debug("REST request to get all DataTypes");
        Sort.Order order1 = new Sort.Order(Sort.Direction.DESC, "name");
        Sort sort = new Sort(order1);
        return dataTypeService.findAll(sort);
    }

    /**
     * GET  /data-types/:id : get the "id" dataType.
     *
     * @param id the id of the dataTypeDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the dataTypeDTO, or with status 404 (Not Found)
     */
    @GetMapping("/data-types/{id}")
//    @Cacheable(value = "DataTypeCache", key = "#id")
    @Timed
    public ResponseEntity<DataType> getDataType(@PathVariable String id) {
        log.debug("REST request to get DataType : {}", id);
        Sort.Order order1 = new Sort.Order(Sort.Direction.DESC, "name");
        Sort sort = new Sort(order1);
        DataType dataTypeDTO = dataTypeService.findOne(id, sort);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(dataTypeDTO));
    }

    /**
     * GET  /data-types/:id : get the "id" dataType.
     *
     * @param name the id of the dataTypeDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the dataTypeDTO, or with status 404 (Not Found)
     */
    @GetMapping("/data-types/query/{name}")
//    @Cacheable(value = "DataTypeCache", key = "#name")
    @Timed
    public List<DataType2DTO> queryDataType(@PathVariable String name) {
        List<DataType2DTO> dataTypeDTOs = dataTypeService.queryByName(name);
        return dataTypeDTOs;
    }

    /**
     * DELETE  /data-types/:id : delete the "id" dataType.
     *
     * @param id the id of the dataTypeDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/data-types/{id}")
//    @CacheEvict(value = {"DataTypeCache"}, allEntries = true)
    @Timed
    public ResponseEntity<Void> deleteDataType(@PathVariable String id) {
        log.debug("REST request to delete DataType : {}", id);
        dataTypeService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }
}
